package com.woniu.woniuYoga.comm.sentinel.block;


import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.woniu.woniuYoga.comm.core.exception.ResultError;
import com.woniu.woniuYoga.comm.core.exception.WoniuExceptionCode;
import com.woniu.woniuYoga.comm.web.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/**
 * @author: 付宽成
 * @description: 自定义 sentinel 全局异常处理(除了被 " @SentinelResource " 注解过的所有请求)
 * @date: 2020/8/24 15:03
 * @version: 1.0
 */
@Component
@Slf4j
public class GlobalBlockException implements BlockExceptionHandler{
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        log.warn(e.getRule().getResource() + "被限流了");
        ResultError re = ResultError.builder()
                .code(WoniuExceptionCode.SENTINEL_BLOCK.getCode())
                .msg(e.getRule().getResource() + "被限流了")
                .build();
        System.out.println(e.getClass().getName());
        response.setContentType("application/json;charset=utf8");
        response.setCharacterEncoding("utf-8");
        response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
        JsonUtil.toJsonStringWrite(response.getOutputStream(),re);
    }
}
